package org.ohos.sample.cordova;

import com.ffsky.litepack.Lite;
import com.ffsky.litepack.logger.L;
import ohos.agp.components.webengine.BrowserAgent;
import ohos.agp.components.webengine.JsMessageResult;
import ohos.agp.components.webengine.WebView;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;

public class SystemBrowserAgent extends BrowserAgent {
    private String TAG="SystemBrowserAgent";
    private WebViewInterface webViewInterface;
    public SystemBrowserAgent(Context context,WebViewInterface webViewInterface) {
        super(context);
        this.webViewInterface = webViewInterface;
    }

    @Override
    public void onTitleUpdated(WebView webView, String title) {
        super.onTitleUpdated(webView, title);
        // 标题变更时自定义处理
        if(webViewInterface!=null){
            webViewInterface.updateWebViewTitle(title);
        }
    }

    @Override
    public void onProgressUpdated(WebView webView, int newProgress) {
        super.onProgressUpdated(webView, newProgress);
        // 加载进度变更时自定义处理
        if(webViewInterface!=null){
            webViewInterface.onWebViewProgressUpdated(newProgress );
        }
    }

    @Override
    public boolean onJsMessageShow(WebView webView, String url, String message, boolean isAlert, JsMessageResult result) {
        L.i(TAG,"onJsMessageShow->URL=",url," ,message=",message,",isAlert=",isAlert);
        if (isAlert) {
            // 将Web页面的alert对话框改为ToastDialog方式提示
            new ToastDialog(Lite.abilityPackage).setText(message).setAlignment(LayoutAlignment.CENTER).show();
            // 对弹框进行确认处理
            result.confirm();
            return true;
        } else {
            return super.onJsMessageShow(webView, url, message, isAlert, result);
        }

    }
}
